// PPH请求调试中间件 - 增强版（从旧部署包迁移）
function logRequests(req, res, next) {
  const timestamp = new Date().toISOString();
  const clientIP = req.ip || req.connection?.remoteAddress || req.socket?.remoteAddress || 'unknown';
  const userAgent = req.get('User-Agent') || 'unknown';
  const origin = req.get('Origin') || req.get('Referer') || 'unknown';

  // 详细的请求日志
  console.log(`\n🌐 [${timestamp}] ${req.method} ${req.path}`);
  console.log(`📍 客户端IP: ${clientIP}`);
  console.log(`🔗 来源: ${origin}`);
  console.log(`🖥️  用户代理: ${userAgent.substring(0, 100)}${userAgent.length > 100 ? '...' : ''}`);

  // 记录查询参数
  try {
    if (req.query && Object.keys(req.query).length > 0) {
      console.log('🔍 查询参数:', req.query);
    }
  } catch (_) {}

  // 对于POST请求，记录body信息（小体积）
  try {
    if (req.method === 'POST' && req.body) {
      const bodyStr = JSON.stringify(req.body);
      const bodySize = bodyStr.length;
      console.log(`📦 请求体大小: ${bodySize} bytes`);
      if (bodySize < 1000) {
        console.log('📝 请求体内容:', req.body);
      }
    }
  } catch (_) {}

  // 记录重要的请求头
  try {
    const importantHeaders = ['content-type', 'authorization', 'x-forwarded-for', 'x-real-ip'];
    importantHeaders.forEach(h => {
      const v = req.get(h);
      if (v) console.log(`📋 ${h}: ${v}`);
    });
  } catch (_) {}

  // 拦截响应以记录状态码和错误
  try {
    const originalSend = res.send.bind(res);
    const originalJson = res.json.bind(res);

    res.send = function(data) {
      console.log(`📤 响应状态: ${res.statusCode}`);
      if (res.statusCode >= 400) console.log('❌ 错误响应:', data);
      return originalSend(data);
    };

    res.json = function(data) {
      console.log(`📤 JSON响应状态: ${res.statusCode}`);
      if (res.statusCode >= 400) {
        console.log('❌ 错误JSON:', data);
      }
      return originalJson(data);
    };
  } catch (_) {}

  next();
}

module.exports = logRequests;

